package sgz.ln.inter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import sgz.ln.excel.ExcelDriver;
import sgz.ln.txt.TxtDriver;

public class MainInterface extends JFrame {
	private static final long serialVersionUID = 4387937858073022268L;
	JFileChooser sourceFile;
	JButton verifyButton;
	JLabel numUnitLabel;
	JTextField numUnitText;

	public MainInterface() {
		super("Excel提取器");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout(null);
		setBounds(300, 200, 400, 300);
		numUnitLabel = new JLabel("隔多少行：");
		numUnitLabel.setBounds(50, 100, 100, 30);
		add(numUnitLabel);
		numUnitText = new JTextField();
		numUnitText.setBounds(160, 100, 50, 30);
		numUnitText.setText("3");
		add(numUnitText);
		verifyButton = new JButton("选择文件");
		verifyButton.setBounds(250, 150, 100, 50);
		verifyButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String numUnitS = numUnitText.getText();
				int numUnitI = -1;
				try {
					numUnitI = Integer.parseInt(numUnitS);
					if (numUnitI < 2 || numUnitI > 10)
						throw new NumberFormatException();
				} catch (NumberFormatException e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(MainInterface.this, "输入有误！！");
					return;
				}
				sourceFile = new JFileChooser();
				sourceFile.showOpenDialog(MainInterface.this);
				File file = sourceFile.getSelectedFile();
				if (file == null)
					return;
				try {
					String filename = file.getName();
					if (filename.endsWith("txt") || filename.endsWith("csv"))
						TxtDriver.extractExcel(file, numUnitI);
					else if (filename.endsWith("xls")
							|| filename.endsWith("xlsx"))
						ExcelDriver.extractExcel(file, numUnitI);
				} catch (IOException e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(MainInterface.this,
							"转换失败！提示：" + e.getMessage());
				}
				JOptionPane.showMessageDialog(MainInterface.this, "转换成功！");
			}
		});
		add(verifyButton);
	}

	public static void main(String[] args) {
		new MainInterface().setVisible(true);
	}
}
